package com.shuguang.medicalcare;



import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private EditText name;
    private EditText phone;
    private CheckBox box;

    public TextView version;

    public String fileName;

    private TextView privacy;

    String apkPath;

    private Boolean flg = true;  // 截留防抖
    private Boolean isTrue = false; //是否同意隐私策略



    public String errStr;

    private  mHandler mhandler=new mHandler(this);





//    https://blog.csdn.net/weixin_42731568/article/details/110383711
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        Log.i("ip", LoginPath);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }


        PackageManager pm =getApplicationContext().getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
            String versionName = pi.versionName;
            int versioncode = pi.versionCode;


            version =(TextView)findViewById(R.id.textView2);
            version.setText("欢迎使用曙光呼 v"+versionName);

//            Toast.makeText(MainActivity.this, "我又回来了？", Toast.LENGTH_SHORT).show();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }






        //获取表单数据
        name = (EditText) findViewById(R.id.name);
        phone = (EditText) findViewById(R.id.phone);
        box = (CheckBox) findViewById(R.id.box1);

        try {
            this.init();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }


    }


    //名称框 限制输入
    public static String stringFilter(String str)throws PatternSyntaxException {
        // 只允许字母、数字和汉字
        String   regEx  =  "[^a-zA-Z0-9\u4E00-\u9FA5]";
        Pattern p   =   Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return   m.replaceAll("").trim();
    }

    //是否是手机号
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    //Handler静态内部类 防止内存泄漏
    private static class mHandler extends Handler {
        WeakReference<MainActivity> weakReference;
        public mHandler(MainActivity mainActivity){
            weakReference = new WeakReference<MainActivity>(mainActivity);
        }
        @Override
        public void handleMessage(Message msg){
            MainActivity mainActivity = weakReference.get();
            if(mainActivity != null){
                   if(msg.what == 2){
                      mainActivity.toast();
                   }

                   if(msg.what == 3){
                      mainActivity.showDialog();
                   }


            }

        }

    }

    public void toast(){
        Toast.makeText(MainActivity.this, errStr, Toast.LENGTH_SHORT).show();
    }

    public void showDialog(){
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MainActivity.this);
        View dialogView = LayoutInflater.from(MainActivity.this)
                .inflate(R.layout.updata,null);

        customizeDialog.setView(dialogView);
        customizeDialog.setCancelable(false);

        AlertDialog alertDialog =  customizeDialog.show();

        Button downBtn = (Button) dialogView.findViewById(R.id.download);

//        PackageManager pm =getApplicationContext().getPackageManager();
//        PackageInfo pi = null;
//        try {
//            pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
//            String versionName = pi.versionName;
//            int versioncode = pi.versionCode;
//
//            downBtn.setText(versionName);
//
//
////            Toast.makeText(MainActivity.this, "我又回来了？", Toast.LENGTH_SHORT).show();
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }

        int max=100,min=1;
        int ran2 = (int) (Math.random()*(max-min)+min);

        int a= (int) new Date().getTime();




        fileName= String.valueOf(ran2) + String.valueOf(a);
//        downBtn.setText(version);

        downBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.i("url+++", apkPath);
//                downBtn.setText(apkPath);
//                Toast.makeText(ListSelect.this, apkPath, Toast.LENGTH_SHORT).show();
//                apkPath







                new DownloadUtils(MainActivity.this,apkPath,"medicalCare"+fileName+".apk");

            }
        });



    }



    private void init() throws PackageManager.NameNotFoundException {
    // 获取登录点击事件监听
        Button btn =(Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.i("登录名称", name.getText().toString() );
//                Log.i("登录电话", phone.getText().toString() );
                String n = name.getText().toString().trim();
                String p = phone.getText().toString().trim();

                if(!isTrue){
                    Toast.makeText(getApplicationContext(),"请勾选隐私策略",Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TextUtils.isEmpty(n)){
                    Toast.makeText(getApplicationContext(),"名称不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TextUtils.isEmpty(p)){
                    Toast.makeText(getApplicationContext(),"手机号不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }

                // if(!isChinaPhoneLegal(p)){
                //     Toast.makeText(getApplicationContext(),"手机号错误",Toast.LENGTH_SHORT).show();
                //     return;
                // }

                if(p.length() != 11){
                    Toast.makeText(getApplicationContext(),"手机号为11位",Toast.LENGTH_SHORT).show();
                    return;
                }

                if(flg){
                    //测试
//                    Intent it= new Intent(getApplicationContext(), ListSelect.class);
//                    startActivity(it);
//                    finish();
                     //测试

                      flg=false;
//                    this.requestLogin();
                      this.requestLoginGet();

                }

            }

            private  void requestLoginGet(){
                Thread myT = new Thread(){
                    @Override
                    public void run() {
//                        get 请求
                        //实例化  里面可能会出现异常，需要try  catch
                        OkHttpClient client = new OkHttpClient();
                        //建立一个Request  通过Builder方法.Url里面填的就是json网址.build创建
//                        http://wxwork.gzsg.cn/wxwork/callcenter/sgCallEnter?hosId=1&userName=%E9%99%88%E4%B8%BD%E5%A9%B7&phoneNumber=13229462139
                        String parm = "?hosId=1&'"+"userName="+name.getText().toString()+"&phoneNumber="+phone.getText().toString();
//                        String path="http://wxwork.gzsg.cn/wxwork/callcenter/sgCallEnter";
                         String path= MedicalCareApi.newPath+"callcenter/sgCallEnter";

                        Log.i("path::", path);

//                        Request request = new Request.Builder().url(path).build();
                        Request.Builder reqBuild = new Request.Builder();
                        HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                                .newBuilder();
                        urlBuilder.addQueryParameter("hosId", "1");
                        urlBuilder.addQueryParameter("userName", name.getText().toString());
                        urlBuilder.addQueryParameter("phoneNumber", phone.getText().toString());
                        reqBuild.url(urlBuilder.build());
                        Request request = reqBuild.build();



                        try {

                            //Response是okhttp实例化，并且调用Request。执行后返回的结果
                            Response response = client.newCall(request).execute();
                            String s = response.body().string();//获取到的json数据

                            Log.i("登录信息::", s);
                            JSONObject jsonObject =  new JSONObject(s);//转成json

                            Integer code = (Integer)jsonObject.getInt("result");

                            if(code == 0){
                                 String myPhone=phone.getText().toString();
                                 String managerId= (String) jsonObject.get("manager_id");
                                 String groupId = (String) jsonObject.get("groupId");
                                 String callerId= (String) jsonObject.getString("callerId");
                                 String userId = (String) jsonObject.get("wxwork_user_id");

                                String appDialType = (String) jsonObject.getString("appDialType");
                                String isAutoDial = (String) jsonObject.getString("isAutoDial");
                                String countDownSeconds = (String) jsonObject.getString("countDownSeconds");
                                String crmDialType = (String) jsonObject.getString("crmDialType");
                                String isRefreshList = (String) jsonObject.getString("isRefreshList");

//                                 String taskId = jsonObject.get("");

                                 SharedPreferences sp = getSharedPreferences("userinfo",MODE_PRIVATE);
                                 SharedPreferences.Editor ed = sp.edit();
                                ed.putString("callerId",callerId);
                                 ed.putString("myPhone",myPhone);
                                 ed.putString("managerId",managerId);
//                                 ed.putString("taskId",taskId);
                                 ed.putString("groupId",groupId);
                                 ed.putString("userId",userId);
                                 ed.putString("token","admin-token");

//                                Log.i("useId", "run: ");

//                                 需要存储 个人 设置信息
//                                {"appDialType":2,"isAutoDial":"0","countDownSeconds":"0","crmDialType":1,"isRefreshList":"0",}
                                ed.putString("appDialType",appDialType);
                                ed.putString("isAutoDial",isAutoDial);
                                ed.putString("countDownSeconds",countDownSeconds);
                                ed.putString("crmDialType",crmDialType);

                                ed.putString("isRefreshList",isRefreshList);





                                 ed.commit();

                                flg=true;

                                Intent it= new Intent(getApplicationContext(), ListSelect.class);
                                startActivity(it);
                                finish();
//                                String str =  listArr.toString();





                            }else{
                                errStr = jsonObject.getString("message");
                                flg=true;
                                Message msg= new Message();
                                msg.what=2;
                                mhandler.sendMessage(msg);
                            }




                        } catch (IOException | JSONException e) {
                            errStr = "网络错误";
                            flg=true;
                            Message msg= new Message();
                            msg.what=2;
                            mhandler.sendMessage(msg);
                            e.printStackTrace();
                        }
                    }
                };
                myT.start();
            }

            private void requestLogin() {
                Log.i("123", "请求: ");
                //post 请求
                Thread myT= new Thread(){
                    @Override
                    public void run(){
                        try {
//                登录            http://wxwork.gzsg.cn/wxwork/callcenter/sgCallEnter?hosId=1&userName=%E9%99%88%E4%B8%BD%E5%A9%B7&phoneNumber=13229462139
//                 任务类型           http://wxwork.gzsg.cn/wxwork/callcenter/workbenchInviteTask?hosId=1&userId=LiHao&managerId=16296974261668
//                 列表           http://wxwork.gzsg.cn/wxwork/callcenter/workbenchInviteTaskCustomerList?taskId=2&groupId=2&hosId=1&userId=LiHao&managerId=16296974261668

                            String path="http://192.168.11.48:3000/medical_api/login";

                            OkHttpClient okHttpClient =new OkHttpClient.Builder()
                            .connectTimeout(10, TimeUnit.SECONDS)
                            .readTimeout(10,TimeUnit.SECONDS)
                            .build();

                            FormBody formBody= new FormBody.Builder()
                                    .add("name", name.getText().toString()).add("phone", phone.getText().toString())
                                    .build();

                            Request request= new Request.Builder()
                                    .post(formBody)
                                    .url(path)
                                    .build();

                            Call call = okHttpClient.newCall(request);

                            call.enqueue(new Callback() {

                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                                    Toast.makeText(getApplicationContext(),"嘿嘿1",Toast.LENGTH_SHORT).show();
//                                    Log.i("yes55555", "嘿嘿嘿5555555555555555555555555555555555555555555555555555555555555555555555555555555555");
//                                    Response response = client.newCall(request).execute();

                                    try {
                                        String s = response.body().string();//获取到的json数据
                                        JSONObject jsonObject = new JSONObject(s);//转成json
                                        Integer code = (Integer)jsonObject.getInt("code");


                                        JSONObject ob= jsonObject.getJSONObject("data");
                                        String token = ob.get("token").toString();
//

//                                        Log.i("str444444444", ob.get("token").toString());

                                        SharedPreferences userSp = getSharedPreferences("userinfo",MODE_PRIVATE);
                                        SharedPreferences.Editor ed=userSp.edit();
                                        ed.putString("token",token);

//                                        ed.putStringSet()


                                        ed.commit();

                                        flg=true;

                                        Intent it= new Intent(getApplicationContext(), ListSelect.class);
                                        startActivity(it);
                                        finish();

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

//


                                }

                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    e.printStackTrace();
                                }
                            });









//                            sleep(3000);
//                            flg=true;
//
//                            Intent it= new Intent(getApplicationContext(),listSelect.class);
//                            startActivity(it);
//                            finish();

                            flg=true;

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                };
                myT.start();

            }
        });

    // 获取输入监听事件
        name.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String editable = name.getText().toString();
                String str = stringFilter(editable.toString());
                if(!editable.equals(str)){
                    name.setText(str);
                    //设置新的光标所在位置
                    name.setSelection(str.length());
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    // checkBox 监听
        box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    Log.i("选中", "onCheckedChanged:1 ");
                    isTrue=true;
                }else {
                    Log.i("没选中", "onCheckedChanged:2 ");
                    isTrue=false;
                }
            }
        });
    //隐私策略
        privacy=(TextView)findViewById(R.id.Privacy);
        privacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it= new Intent(getApplicationContext(), Privacy.class);
                startActivity(it);
            }
        });


        test();
    }

    public  String toCover(String str){
        StringBuffer stringBuffer= new StringBuffer("");
        for(int i=0;i<str.length();i++){
            if(str.charAt(i) !='.'){
                stringBuffer.append(str.charAt(i));
            }
        }
        return  stringBuffer.toString();
    }

    public void test() throws PackageManager.NameNotFoundException {

        PackageManager pm =getApplicationContext().getPackageManager();
        PackageInfo pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);

        String versionName = pi.versionName;
        int versioncode = pi.versionCode;


        (new Thread(){
            @Override
            public void run() {

                //实例化  里面可能会出现异常，需要try  catch
                OkHttpClient client = new OkHttpClient();

                String path= MedicalCareApi.newPath+"callcenter/checkVersion";


//            http://49.234.94.134:8081/ccapp/callcenter/checkVersion?type=6&now_version=1.0.0

//                        Request request = new Request.Builder().url(path).build();
                Request.Builder reqBuild = new Request.Builder();
                HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                        .newBuilder();
                urlBuilder.addQueryParameter("type", "6");
                urlBuilder.addQueryParameter("now_version", toCover(String.valueOf(versionName))  );

                Log.i("versionName", toCover(String.valueOf(versionName)));

                reqBuild.url(urlBuilder.build());
                Request request = reqBuild.build();



                try {

                    //Response是okhttp实例化，并且调用Request。执行后返回的结果
                    Response response = client.newCall(request).execute();
                    String s = response.body().string();//获取到的json数据
                    Log.i("path::", path);

                    JSONObject jsonObject =  new JSONObject(s);//转成json
                    int code = jsonObject.getInt("code");

//                    Log.i("jsonObject", String.valueOf(jsonObject.getInt("apk")) );
                    Log.i("版本号", s  );
                    if(code == 0){
//                                    无需更新




                    }

                    if(code == 1){

//                                    需要更新


                        Message msg = new Message();
                        msg.what=3;
                        mhandler.sendMessage(msg);

                        apkPath=jsonObject.getString("apk");

                        Log.i("apkName", apkPath);

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                }




            }
        }).start();









    }


}